package com.bainuo.doctor.common.image_support.imghandle.crop;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.os.Build;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;

import com.bainuo.doctor.common.R;
import com.bainuo.doctor.common.base.BaseActivity;
import com.bainuo.doctor.common.util.ViewUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.ButterKnife;
import com.global.Global;

public class ImageCropAvtivity extends BaseActivity {

//    @BindView(R.id.crop_imageView)
    ImageView mImageView;
//    @BindView(R.id.crop_frame_view)
    ImageView mFrameView;

    public static Bitmap cropBitmap = null;

    public static String BUNDLE_IMAGEPATH = "imagePath";
    public static String BUNDLE_IMAGEWIDTH = "imageWidth";

//    public static String BUNDLE_NEW_PATH = "BUNDLE_NEW_PATH";
//    public static String BUNDLE_IMAGEHEIGHT = "imageHeight";


    public int imageWidth;
    public int imageHeight;
    /**
     * 图片路径
     */
    private String imagePath;

    /**
     * 原位图
     */
    private Bitmap srcBitmap;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentViewWithRoot(R.layout.activity_image_crop_avtivity);
        ButterKnife.bind(this);

        mImageView = (ImageView)findViewById(R.id.crop_imageView);
        mFrameView = (ImageView)findViewById(R.id.crop_frame_view);
    }

    @Override
    public void initView() {

        imageWidth = getIntent().getIntExtra(BUNDLE_IMAGEWIDTH, 300);
//        imageWidth = imageWidth;
//        imageHeight = getIntent().getIntExtra(BUNDLE_IMAGEHEIGHT,320);
        imagePath = getIntent().getStringExtra(BUNDLE_IMAGEPATH);
        if (imagePath != null) {

            getToolbar().setMainTitleRightText("使用");
            getToolbar().setListener(this);

            mImageView.setOnTouchListener(new TouchListener());
            srcBitmap = BitmapFactory.decodeFile(imagePath);

            if (srcBitmap == null)
                return;

            mImageView.setImageBitmap(srcBitmap);
            ViewUtil.setCorner(mFrameView, 3, 0, "#000000", null);

            mImageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    if (mImageView.getWidth() != 0) {
                        int w = mImageView.getWidth() * 2 / 3;
                        ViewUtil.setViewSize(mFrameView, w, w);

                        int bitmapWidth = srcBitmap.getWidth();
                        int bitmapHeight = srcBitmap.getHeight();
                        if (bitmapWidth != 0 && bitmapHeight != 0) {

                            Matrix currentMatrix = mImageView.getImageMatrix();


                            //将图片放置在中间
                            currentMatrix.setTranslate((mImageView.getWidth() - bitmapWidth) / 2,
                                    (mImageView.getHeight() - bitmapHeight) / 2);
//                            LogUtils.e("123","--->vw "+mImageView.getWidth()+" w "+srcBitmap.getWidth()+" s "+scale);


                            //计算放大倍数 适应中间
                            float scale;
                            if (bitmapWidth > bitmapHeight)
                                scale = w * 1.0f / bitmapHeight;
                            else
                                scale = w * 1.0f / srcBitmap.getWidth();

                            //将图片放大到屏幕宽度
                            currentMatrix.postScale(scale, scale,
                                    mImageView.getWidth() / 2,
                                    mImageView.getHeight() / 2);
                            mImageView.setImageMatrix(currentMatrix);
                        }

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                            mImageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                        }
                    }
                }
            });
        }

    }

    private final class TouchListener implements View.OnTouchListener {

        private int mode = 0;
        private static final int MODE_DRAG = 1;
        private static final int MODE_ZOOM = 2;

        private PointF startPoint = new PointF();
        private Matrix matrix = new Matrix();
        private Matrix currentMatrix = new Matrix();

        private float startDis;
        private PointF midPoint;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction() & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_DOWN:
                    mode = MODE_DRAG;
                    currentMatrix.set(mImageView.getImageMatrix());
                    startPoint.set(event.getX(), event.getY());
                    break;
                case MotionEvent.ACTION_MOVE:
                    if (mode == MODE_DRAG) {
                        float dx = event.getX() - startPoint.x;
                        float dy = event.getY() - startPoint.y;
                        matrix.set(currentMatrix);
                        matrix.postTranslate(dx, dy);
                    } else if (mode == MODE_ZOOM) {
                        float endDis = distance(event);
                        if (endDis > 10f) {
                            float scale = endDis / startDis;
                            matrix.set(currentMatrix);
                            matrix.postScale(scale, scale, midPoint.x, midPoint.y);
                        }
                    }
                    break;
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_POINTER_UP:
                    mode = 0;
                    break;
                case MotionEvent.ACTION_POINTER_DOWN:
                    mode = MODE_ZOOM;
                    startDis = distance(event);
                    if (startDis > 10f) {
                        midPoint = mid(event);
                        currentMatrix.set(mImageView.getImageMatrix());
                    }
                    break;
            }
            mImageView.setImageMatrix(matrix);
            return true;
        }

        private float distance(MotionEvent event) {
            float dx = event.getX(1) - event.getX(0);
            float dy = event.getY(1) - event.getY(0);
            return (float) Math.sqrt(dx * dx + dy * dy);
        }

        private PointF mid(MotionEvent event) {
            float midX = (event.getX(1) + event.getX(0)) / 2;
            float midY = (event.getY(1) + event.getY(0)) / 2;
            return new PointF(midX, midY);
        }

    }


    @Override
    public void onRightIconClickListener(View rightView) {
        super.onRightIconClickListener(rightView);

        Matrix matrix = mImageView.getImageMatrix();
        float[] values = new float[9];
        matrix.getValues(values);


        int left = mFrameView.getLeft();
        int top = mFrameView.getTop();
        int w = mFrameView.getWidth();
        float scale = values[Matrix.MSCALE_X];

        //计算当前x y 在图片的偏移
        int x = (int) ((left - values[Matrix.MTRANS_X]) / scale);
        int y = (int) ((top - values[Matrix.MTRANS_Y]) / scale);
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(imagePath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;


        Bitmap bitmap = BitmapFactory.decodeStream(fis, null, opt);


        //计算宽高 防止视图移出外面截图出错
        int cropw = (int) Math.min(bitmap.getWidth() - x, w / scale);
        int croph = (int) Math.min(bitmap.getHeight() - y, w / scale);

        Bitmap newBitmap = Bitmap.createBitmap(bitmap,
                Math.max(0, x),
                Math.max(0, y),
                cropw,
                croph);


        if (cropw > imageWidth || cropw > imageHeight) {
            newBitmap = Bitmap.createScaledBitmap(newBitmap,imageWidth,imageWidth,false);
        }

        String path = Global.getPathWithRoot("tmp")+"/avatar.jpg.tmp";

        try {

            FileOutputStream out = new FileOutputStream(new File(path));
            newBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

        Intent intent = new Intent();
        intent.putExtra(BUNDLE_IMAGEPATH,path);
        setResult(RESULT_OK, intent);
        finish();
    }
}
